import frpOption from "../option.json" with { type: "json" }
import { getOrderId, getProductionOrderList } from "./util.js"
import logger from "./logger.js"

import { getStorageKey, localStorage, StorageKeyType } from "./localStorage.js"

// 原逻辑
// async function colorDiff(orderCode, productionOrderList) {
//     const storageKey = getStorageKey(orderCode, StorageKeyType.colorDiff)
//     let colorDiffStatus = JSON.parse(localStorage.getItem(storageKey))
//     if (colorDiffStatus == null) {
//         colorDiffStatus = {
//             firstFinish: [],
//             secondFinish: []
//         }
//     }

//     if (colorDiffStatus.firstFinish.length !== productionOrderList.length) {
//         // 第一次色差档
//         const orderColorDiffRes = await fetch(`${frpOption.api.colorDiff_1}?code=${orderCode}`).then((res) => res.json())
//         if (orderColorDiffRes?.param1?.errMsg != null) {
//             throw new Error("第一次色差档错误：" + orderColorDiffRes.param1.errMsg)
//         }
//         logger.info(`${orderCode} 第一次色差档成功`)

//         const successCode = orderColorDiffRes.param1.confirmedProductionOrders.map(item => item.code)
//         colorDiffStatus.firstFinish.push(...successCode)
//         localStorage.setItem(storageKey, JSON.stringify(colorDiffStatus))
//     }

//     const runProductionList = productionOrderList.filter(item => !colorDiffStatus.secondFinish.includes(item.code))

//     // 第二次色差档
//     const {
//         successCodeList,
//         errorMsgList
//     } = await batchColorDiff_2(orderCode, runProductionList)

//     colorDiffStatus.secondFinish.push(...successCodeList)
//     localStorage.setItem(storageKey, JSON.stringify(colorDiffStatus))

//     if (errorMsgList.length > 0) {
//         throw new Error('\n' + errorMsgList.join("\n"))
//     }
// }

// 现在不需要执行第一次色差档
async function colorDiff(orderCode, productionOrderList) {
    const storageKey = getStorageKey(orderCode, StorageKeyType.colorDiff)
    let colorDiffStatus = JSON.parse(localStorage.getItem(storageKey))
    if (colorDiffStatus == null) {
        colorDiffStatus = {
            firstFinish: [],
            secondFinish: []
        }
    }

    const runProductionList = productionOrderList.filter(item => !colorDiffStatus.secondFinish.includes(item.code))

    // 第二次色差档
    const {
        successCodeList,
        errorMsgList
    } = await batchColorDiff_2(orderCode, runProductionList)

    colorDiffStatus.secondFinish.push(...successCodeList)
    localStorage.setItem(storageKey, JSON.stringify(colorDiffStatus))

    if (errorMsgList.length > 0) {
        throw new Error('\n' + errorMsgList.join("\n"))
    }
}

async function batchColorDiff_2(orderCode, productionOrderList) {
    if (!productionOrderList) {
        const orderId = await getOrderId(orderCode)
        productionOrderList = await getProductionOrderList(orderId)
    }
    const productionCodeList = productionOrderList.map((item) => item.code)

    const errorMsgList = []
    const successCodeList = []
    for (const code of productionCodeList) {
        // if (hasConfirmedProductionOrderCodeList && !hasConfirmedProductionOrderCodeList.includes(code)) {
        //     errorMsgList.push(`${code} 第一步色差档失败`)
        //     continue
        // }

        try {
            await colorDiff_2(code)
            successCodeList.push(code)
            logger.info(`${code} 色差档成功`)
        } catch (err) {
            errorMsgList.push(err.message)
        }
    }

    return {
        successCodeList: successCodeList,
        errorMsgList: errorMsgList
    }
}

async function colorDiff_2(productionCode) {
    // 原色差档
    // const productionColorDiffRes = await fetch(`${frpOption.api.colorDiff_2}?code=${productionCode}`).then((res) => res.json())
    // 不用判断apsStatus
    const productionColorDiffRes = await fetch(`${frpOption.api.colorDiff_2_temp}?code=${productionCode}`).then((res) => res.json())
    let errMsg = productionColorDiffRes?.param1?.errMsg
    if (!(typeof errMsg === 'object' && JSON.stringify(errMsg) === '{}')) {
        if (typeof errMsg === 'object') {
            errMsg = JSON.stringify(errMsg || productionColorDiffRes)
        }
        throw new Error(productionCode + " 第二次色差档失败：" + errMsg)
    }
}

export { colorDiff, batchColorDiff_2 }
